var ws;

window.onload = ToggleConnection;

function ToggleConnection() {

    try {
        if ("WebSocket" in window) {
            ws = new WebSocket("ws://localhost:8080/nw/websocket");
            ws.onopen = function (event) {
                console.log("已经与服务器建立了连接\r\n当前连接状态：" + this.readyState);
            };
            ws.onmessage = function (event) {
                getMessage(event.data);
                console.log("接收到服务器发送的数据：\r\n" + event.data);
            };
            ws.onclose = function (event) {
                console.log("已经与服务器断开连接\r\n当前连接状态：" + this.readyState);
            };
            ws.onerror = function (event) {
                console.log("WebSocket异常！");
            };
        } else {
            console.log("请升级您的浏览器");
        }
    } catch (ex) {
        console.log(ex.message);
    }
};

window.onbeforeunload = function () {
    ws.close();
};

function sendData(data) {
    try {
        ws.send(data);
    } catch (ex) {
        alert(ex.message);
    }
};
